package com.homelock.processor;

import com.alibaba.fastjson.JSON;
import com.homelock.common.enums.ServiceTypeEnum;
import com.homelock.constants.LockCmdEnum;
import com.homelock.constants.ZxAlarmTypeEnum;
import com.homelock.constants.ZxUserTypeEnum;
import com.homelock.entity.HlDevInfo;
import com.homelock.entity.HlDevUserUnlock;
import com.homelock.entity.HlOpenDoorRecord;
import com.homelock.service.HlDevInfoService;
import com.homelock.service.HlDevUserUnlockService;
import com.homelock.service.LockOpenRecordService;
import com.pi.base.util.lang.ByteUtil;
import com.pi.smart.client.ins.comm.domain.BaseWifiCmd;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 开门记录上传
 */
@CmdMeta(values={LockCmdEnum.OPEN_RECORD,LockCmdEnum.ALARM_RECORD})
@Component
public class ZxLockOpenRecordProcessor implements BaseMsgProcessor {
    private static final Logger logger = LoggerFactory.getLogger(ZxLockOpenRecordProcessor.class);

    @Autowired
    private HlDevInfoService hlDevInfoService;
    @Autowired
    private LockOpenRecordService lockOpenRecordService;;
    @Autowired
    private HlDevUserUnlockService hlDevUserUnlockService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handle(BaseWifiCmd message) {
        HlDevInfo devInfo = hlDevInfoService.findOneByDevCodeAndStateTrue(message.getDevCode());
        if(null == devInfo){
            logger.info("[振兴锁设备用户handle]查询不到相关设备，devCode=",message.getDevCode());
            return;
        }
        byte[] ins = message.getCmd();
        byte electornic = ins[2];
        byte userType = ins[3] ;
        logger.info("userType:{}",userType);
        logger.info("recordType:{}",ins[1]&0XFF);
        byte[] idArray = new byte[2];
        System.arraycopy(ins,4,idArray,0,2);
        int userId = ByteUtil.byteToInt(idArray).intValue();
        byte alarmType = ins[2];
        HlOpenDoorRecord record = new HlOpenDoorRecord();
        // 设备id
        record.setDevId(devInfo.getId());
        record.setSourceId(Optional.ofNullable(devInfo.getSourceId()).orElse(0L));
        record.setCommunityId(Optional.ofNullable(devInfo.getCommunityId()).orElse(0L));
        // 锁上传的用户id
        record.setTriggerUserId(String.valueOf(userId));
        record.setTriggerId(userId);
        // 锁查询对应的unlock表的id （普通开门有 报警无)
        if(LockCmdEnum.ALARM_RECORD.getOptCode() == (ins[1] & 0xFF) ){
            // 报警记录
            record.setRecordType(ServiceTypeEnum.Alarm.getType().byteValue());
            ZxAlarmTypeEnum zxAlarmTypeEnum = ZxAlarmTypeEnum.codeValue(alarmType);

            record.setTriggerName(null != zxAlarmTypeEnum ? zxAlarmTypeEnum.getName() : StringUtils.EMPTY);
            record.setTriggerSourceId(0L);
            record.setTriggerUnlockId(0L);
            // 报警类型 = recordType+alarmType 2开头的数字
            record.setTriggerType(ServiceTypeEnum.Alarm.getType()*10+alarmType);
            logger.info("操作类型：{}，新增报警记录->开门用户id:{},开门方式：{}",ins[1],alarmType,userId);
        }else {
            // 更新电量
            hlDevInfoService.updateBatteryAndVersionById(devInfo.getId(),electornic,devInfo.getVersion()+1);
            logger.info("[振兴锁开门记录]电量更新成功:{},{}",devInfo.getId(),electornic);
            // 普通开门记录
            record.setRecordType(ServiceTypeEnum.MESSAGE.getType().byteValue());
            // 开门类型 = recordType+openType 2开头的数字
            record.setTriggerType((ServiceTypeEnum.MESSAGE.getType()*10+ userType));
            HlDevUserUnlock unlock = hlDevUserUnlockService.queryByDevIdAndUnlockTypeAndUnlockId(devInfo.getId(),userType,String.valueOf(userId));
            long unlockId = Optional.ofNullable(unlock).map(HlDevUserUnlock::getId).orElse(0L);
            // unlock表的id
            record.setTriggerSourceId(unlockId);
            record.setTriggerUnlockId(unlockId);
            // 开门方式名称
            if(null != unlock ){
                record.setTriggerName(Optional.ofNullable(ZxUserTypeEnum.codeValue(unlock.getUnlockType()).getTypeName()).orElse(""));
            }else{
                // 取当前上传的开门记录的type 以及userId
                record.setTriggerName(Optional.ofNullable(ZxUserTypeEnum.codeValue(userType).getTypeName()).orElse(""));
            }
            logger.info("操作类型：{}，新增普通开门记录->开门用户id:{},开门方式：{}",ins[1],userType,userId);
        }
        if(record.getTriggerType()==27){
            HlDevUserUnlock unlock = hlDevUserUnlockService.findOneByDevIdAnUnlockIdAndStatusTrue(record.getDevId(),
                    record.getTriggerId() + "");
            if( unlock.getUnlockType() == 1 & unlock.getUnlockPhase()==2) {
                lockOpenRecordService.sendZxSms(record, devInfo.getId(), devInfo);
            }
        }else{
            lockOpenRecordService.sendZxSms(record, devInfo.getId(), devInfo);
        }

        logger.info("[alarm_send_succeed] devId: {}", devInfo.getId());
        lockOpenRecordService.insertZxLock(record);
        logger.info("[振兴锁开门记录]上传成功:{}",JSON.toJSONString(record));

    }
}
